﻿IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Save/*--EntryName--*/]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Save/*--EntryName--*/]
GO

CREATE PROCEDURE [dbo].[Save/*--EntryName--*/]
	@UserRoles TNVarCharSet READONLY,
	@PathOrId nvarchar(MAX),
	@Name nvarchar(256), 
	@Parent nvarchar(MAX),
	@NewId bigint OUTPUT,
/*--AdditionalArgs--*/
	@AccessControlList TAccessControlList READONLY
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @ParentId bigint = NULL
	
	IF @PathOrId IS NULL
	BEGIN
		EXEC GetDirectoryEntryId @Parent, 2, @Id = @ParentId OUTPUT

		IF @ParentId IS NULL OR dbo.HasPermission(@UserRoles, @ParentId, 1) = 0 RETURN 1

		IF EXISTS(
			SELECT Id 
			FROM DirectoryEntry 
			WHERE 
				ParentId = @ParentId AND Name = @Name
		) RETURN 4

		IF dbo.HasPermission(@UserRoles, @ParentId, 4) = 0 RETURN 3

		INSERT INTO DirectoryEntry(Name, ParentId, CreatedOn, UpdatedOn, [Type])
		VALUES(@Name, @ParentId, GETUTCDATE(), GETUTCDATE(), /*--DirectoryEntryType--*/)
		
		SET @NewId = @@IDENTITY

/*--SpecificDataInsertion--*/
	END
	ELSE
	BEGIN
		DECLARE @Id bigint
		
		EXEC GetDirectoryEntryId @PathOrId, 0, @Id = @Id OUTPUT

		IF @Id IS NULL
		BEGIN
			RETURN 2
		END

		IF NOT @Parent IS NULL
		BEGIN
			EXEC GetDirectoryEntryId @Parent, 2, @Id = @ParentId OUTPUT

			IF @ParentId IS NULL OR dbo.HasPermission(@UserRoles, @ParentId, 1) = 0 RETURN 1

			IF EXISTS(
				SELECT Id 
				FROM DirectoryEntry 
				WHERE 
					ParentId = @ParentId AND 
					Id <> @Id AND
					Name = @Name
			) RETURN 4
		END

		IF dbo.HasPermission(@UserRoles, @Id, 2) = 0 RETURN 3

		DECLARE @Type int

		SELECT @Type = [Type]
		FROM DirectoryEntry
		WHERE Id = @Id

		IF @Type IS NULL OR @Type <> /*--DirectoryEntryType--*/
		BEGIN
			RETURN 2
		END
		
		UPDATE DirectoryEntry
		SET
			Name = @Name,
			ParentId = ISNULL(@ParentId, ParentId)
		WHERE
			Id = @Id

/*--SpecificDataUpdate--*/
		
		SET @NewId = @Id

		DELETE AccessControlList
		WHERE DirectoryEntryId = @Id
	END

	INSERT INTO AccessControlList(DirectoryEntryId, [Role], Permission)
	SELECT @NewId, [Role], Permission
	FROM @AccessControlList

	RETURN 0
END
GO
